import React, { Component } from 'react'

export default class New extends Component {
  constructor () {
    super()

    this.state = {
      username: '张三',
      age: 100
    }
    console.log('---new constructor---')
  }

  // 拦截
  static getDerivedStateFromProps (props, state) {
    console.log('---getDerivedStateFromProps---', props, state)

    // 默认实现 显示张三
    return { ...props, ...state }
    // return {
    //   // 会把张三拦截为 里斯
    //   username: '里斯',
    //   age: 1
    // }
  }

  componentDidMount () {
    console.log('---componentDidMount---')
  }

  shouldComponentUpdate () {
    console.log('--shouldComponentUpdate--')
    // return false
    return true
  }

  // 更新之前获取快照（儿时记忆）
  getSnapshotBeforeUpdate (prevProps, prevState) {
    console.log('--getSnapshotBeforeUpdate--', prevProps, prevState)
  }

  // 第三个参数snapshot：拿到快照（儿时记忆）传递过来的值
  componentDidUpdate (prevProps, prevState, snapshot) {
    console.log('--snapshot--', snapshot)
  }
  render () {
    console.log('--new render--')
    return (
      <div>
        New
        <p>
          username is {this.state.username} age is {this.props.age}
        </p>
        <p>
          <button
            onClick={() => {
              this.setState({ username: '王五' })
            }}
          >
            change
          </button>
        </p>
      </div>
    )
  }
  componentWillUnmount () {
    console.log('---componentWillUnmount--')
  }
}
